/*

 Authors: ZhangXuelian
 	
 
 Changes:
 	
	
*/

#include "msg_result.h"

EVENT create_event()
{
	EVENT ev = (EVENT)malloc(sizeof(THREAD_EVENT));
	if (ev)
	{
		ev->var = 0;
		if (pthread_cond_init(&ev->cond, NULL) == 0)
		{
			if (pthread_mutex_init(&ev->mutex, NULL) != 0)
			{
				pthread_cond_destroy(&ev->cond);
				free(ev);
				ev = NULL;
			}
		}
		else
		{
			free(ev);
			ev = NULL;
		}
	}
	return ev;
}

void delete_event(EVENT ev)
{
	if (ev)
	{
		pthread_mutex_destroy(&ev->mutex);
		pthread_cond_destroy(&ev->cond);
		free(ev);
	}
}

int wait_event(EVENT ev, unsigned long wait_time)
{
	int ret = 0;
	if (ev)
	{
		struct timeval now;
		struct timespec timeout;
		long long nsec;
		gettimeofday(&now, NULL);
		nsec = now.tv_sec*1000000000ll + now.tv_usec * 1000ll + wait_time*1000000ll;
		timeout.tv_sec = nsec / 1000000000ll;
		timeout.tv_nsec = nsec % 1000000000ll;
		pthread_mutex_lock(&ev->mutex);            
		while (ev->var != 1 && ret == 0)
		{
			ret = pthread_cond_timedwait(&ev->cond, &ev->mutex, &timeout);
		}
		ev->var = 0;
		pthread_mutex_unlock(&ev->mutex);
		return ret;
	}
	return -1;
}

signed char set_event(EVENT ev)
{
	if (ev)
	{
		pthread_mutex_lock(&ev->mutex);           
		ev->var = 1;
		pthread_cond_signal(&ev->cond);
		pthread_mutex_unlock(&ev->mutex);   
		return 1;
	}
	return 0;
}

